﻿(function () {
    "use strict";

    var appView = Windows.UI.ViewManagement.ApplicationView;
    var appViewState = Windows.UI.ViewManagement.ApplicationViewState;
    var nav = WinJS.Navigation;
    var ui = WinJS.UI;
    var app = WinJS.Application;
    var activation = Windows.ApplicationModel.Activation;
    var resultListView;
    var btnMore;

    //Itens carregados por página
    var _itensPerPage = 40;

    //Handler que captura o evento de animação da listView e manipula a paginação
    WinJS.UI.eventHandler(listViewLoadingState);
    WinJS.Namespace.define("searchResult", { loadingStateHandler: listViewLoadingState });

    WinJS.UI.Pages.define("/pages/searchResult/searchResult.html", {

        itemInvoked: function (args) {
            var item = args.detail;
            nav.navigate("/pages/itemdetail/itemdetail.html", { itemID: item.itemPromise._value.data.ID });
        },

        ready: function (element, options) {

            //Configurações iniciais de paginação
            WinJS.Application.sessionState.currentPage = 1;

            resultListView = document.querySelector('#imageTextList').winControl;

            element.querySelector('#btnMore').addEventListener('click', btnMoreClick, false);
            btnMore = element.querySelector('#btnMore');
            btnMore.style.display = 'none';

            resultListView.oniteminvoked = this.itemInvoked.bind(this);
            resultListView.oncontentanimating = searchResult.loadingStateHandler;

            if (options.searchText != null)
                searchProcess(options.searchText);
            else
            {
                if (WinJS.Application.sessionState.WSDataSource != null || WinJS.Application.sessionState.WSDataSource != undefined) {
                    resultListView.itemDataSource = WinJS.Application.sessionState.WSDataSource.dataSource;
                    btnMore.style.display = 'block';
                }
            }

            options.searchText = null;
        },

        unload: function () {
            // TODO: Respond to navigations away from this page.
            //WinJS.Application.sessionState.WSDataSource = null;
            resultListView.itemDataSource = null;
        }, 

        updateLayout: function (element, viewState, lastViewState) {
            /// <param name="element" domElement="true" />

            // TODO: Respond to changes in viewState.
        }
    });

    function btnMoreClick(event)
    {
        var currentPage = WinJS.Application.sessionState.currentPage;

        if (currentPage == null || currentPage == undefined)
            currentPage = 1;
        else
            currentPage++;

        WinJS.Application.sessionState.currentPage = currentPage;

        searchProcess(WinJS.Application.sessionState.queryText, currentPage.toString());
    }

    function btnSearchClick(event) {

        var prog = document.getElementById('prgSearch');
        var f = document.getElementById('textBusca');

        if (event.keyCode == 13) {
            searchProcess(f.value, "1");
        }
    }

    function searchProcess(searchText, page)
    {
        try
        {
            WinJS.Application.sessionState.queryText = searchText;

            progressSearch(true);

            var data = WindowsStoreWRC.WRCServiceCom;

            if (page == null || page == undefined)
                page = 1;

            data.buscaProgramas(searchText, page, _itensPerPage).then(
            function complete(result) {
                var JSONResult = JSON.parse(result);

                if (JSONResult.length == _itensPerPage)
                    btnMore.style.display = 'block';
                else
                    btnMore.style.display = 'none';

                for (var i = 0; i < JSONResult.length; i++) {
                    JSONResult[i].Paid = ((JSONResult[i].Paid == false) ? "Gratuito" : "Gratuito para testar");
                    JSONResult[i].RateInteger = parseInt(JSONResult[i].Rate);
                }

                var BindList = new WinJS.Binding.List(JSONResult);
                WinJS.Namespace.define("WSSample", { data: BindList });

                var actualSource = WSSample.data;

                if (WinJS.Application.sessionState.currentPage > 1)
                {
                    var oldSource = WinJS.Application.sessionState.WSDataSource;
                    actualSource = oldSource.concat(actualSource._getArray());
                    actualSource = new WinJS.Binding.List(actualSource);
                    resultListView.itemDataSource = actualSource.dataSource;
                }
                else
                    resultListView.itemDataSource = actualSource.dataSource;

                //Chamar o forceLayout para garantir que irá ordernar os indices do List
                resultListView.forceLayout();
                resultListView.indexOfFirstVisible = 0;

                WinJS.Application.sessionState.WSDataSource = actualSource;

                progressSearch(false);
            },
            function error(result) {
                (new Windows.UI.Popups.MessageDialog(result).showAsync());
            },
            function progress() {
                progressSearch(true);
            });
        }
        catch (error) {
            (new Windows.UI.Popups.MessageDialog("Problemas de conexão com o servidor.").showAsync());
        }
    }

    function listViewLoadingState(event) {
        //Fixa o foco de navegação no primeiro item da próxima pagina
        event.target.winControl.indexOfFirstVisible = ((WinJS.Application.sessionState.currentPage * _itensPerPage)-_itensPerPage);
    }

    function progressSearch(onoff)
    {
        var divprogress = document.getElementById('searchProgress');

        if (divprogress.hasChildNodes()) {
            while (divprogress.firstChild) divprogress.removeChild(divprogress.firstChild);
        }

        if (onoff) {
            divprogress.appendChild(document.createElement("progress"));
            var eleprogress = divprogress.querySelector("progress");
            WinJS.Utilities.addClass(eleprogress, "win-large");
        }
    }

})();
